﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(StartDlg *sdlg,QWidget *parent) :
    QMainWindow(parent),word(0),excel(0),isWPS(false),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
    //StartDlg sdlg(this);
    hide();
    setFixedSize(389,306);
    ui->numEdit->setVisible(false);
    //sdlg.show();
    //sdlg.repaint();
    sdlg->setStatus(QStringLiteral("正在初始化Excel..."));
    excel = new QAxObject("Excel.Application");
    //excel = new QAxObject("ET.Application");
    if(excel->isNull()){
        sdlg->setStatus(QStringLiteral("正在初始化WPS Excel..."));
        excel = new QAxObject("ET.Application");
        if(excel->isNull()){
            sdlg->setStatus(QStringLiteral("初始化失败!"));
            QTimer *timer = new QTimer(this);
            QObject::connect(timer,&QTimer::timeout,[](){
                exit(1);
            });
            timer->start(5000);
        }
        isWPS = true;
    }
    excel->setProperty("Visible",false);
    sdlg->setStatus(QStringLiteral("正在初始化Word..."));
    word = new QAxObject("Word.Application");
    //word = new QAxObject("WPS.Application");
    if(word->isNull()){
        sdlg->setStatus(QStringLiteral("正在初始化WPS Word..."));
        word = new QAxObject("WPS.Application");
        if(word->isNull()){
            sdlg->setStatus(QStringLiteral("初始化失败!"));
            QTimer *timer = new QTimer(this);
            QObject::connect(timer,&QTimer::timeout,[](){
                exit(1);
            });
            timer->start(5000);
        }
        isWPS = true;
    }
    word->setProperty("DisplayAlerts",false);
    excel->setProperty("DisplayAlerts",false);
    word->setProperty("Visible",false);
    excel->setProperty("Visible",false);
    sdlg->setStatus(QStringLiteral("正在创建映射..."));
    sdlg->setVisible(false);
    QObject::connect(this,&MainWindow::closed,[&](){
        delete this;
    });
    delete sdlg;
}

void MainWindow::exception_1(){
    qDebug()<<"Error 23:";
    ui->inFileButton->setEnabled(true);
    ui->status_label_2->setText(QStringLiteral("文件格式错误，请检查!"));
    word->querySubObject("ActiveDocument")->dynamicCall("Close (boolean)", false);
    throw 1;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *){
    hide();
    if(!word->isNull()){
        word->dynamicCall("Quit()");
        delete word;
    }
    if(excel&&!excel->isNull()){
        excel->dynamicCall("Quit()");
        delete excel;
    }
    qDebug()<<"EXIT";
    emit closed();
}

void MainWindow::on_inFileButton_clicked()
{
    inWord = QDir::toNativeSeparators(QFileDialog::getOpenFileName(this,QStringLiteral("选择模板文件"),QDir::currentPath(),
                                          QStringLiteral("Word文档(*.doc);;All files(*.*)")));
    ui->inFilePathEdit->setText(inWord);
    ui->inFilePathEdit->repaint();
    try{
        if(inWord.isEmpty() == false)
            getModelInfo();
    }catch(...){
        qDebug()<<"Error 2:";
    }
}

void MainWindow::on_inFileButton_2_clicked()
{
    inExcel = QDir::toNativeSeparators(QFileDialog::getOpenFileName(this,QStringLiteral("选择班级通讯录"),QDir::currentPath(),
                                                             QStringLiteral("Excel文档(*.xls);;All files(*.*)")));
    ui->inFileExcel->setText(inExcel);
    ui->inFileExcel->repaint();
    if(inExcel.isEmpty() == false)
        getAllList();
}

void MainWindow::initExcel(const QString &path){
//    ui->status_label->setText(QStringLiteral("正在初始化Excel..."));
//    ui->status_label->repaint();
//    excel = new QAxObject("Excel.Application");
//    excel->setProperty("Visible",false);
    ui->status_label->setText(QStringLiteral("正在初始化文件..."));
    ui->status_label->repaint();
    //QAxObject * workbooks = excel->querySubObject("WorkBooks");
    excel->querySubObject("WorkBooks")->dynamicCall("Open(const QString&)",path);
    //QAxObject * workbook = excel->querySubObject("ActiveWorkBook");
    worksheet = excel->querySubObject("ActiveWorkBook")->querySubObject("Worksheets(int)",1);
    ui->status_label->setText(QStringLiteral("正在分析文件..."));
    ui->status_label->repaint();
    QAxObject * usedrange = worksheet->querySubObject("UsedRange");
    count = usedrange->querySubObject("Rows")->property("Count").toInt();
    row_start = usedrange->querySubObject("Rows")->property("Row").toInt();
    col_start = usedrange->querySubObject("Columns")->property("Column").toInt();
    delete usedrange;
}

const QString MainWindow::getCellByExcel(int row, int col){
    //QAxObject * range = worksheet->querySubObject("Cells(int,int)", row, col );
    if(isWPS){
        QString range = QString("%1%2").arg(char('A'+col-1)).arg(row);
        qDebug()<<range;
        return worksheet->querySubObject("Range(const QString&)",range)->property("Text").toString();
    }
    return worksheet->querySubObject("Cells(int,int)",row,col)->property("Value").toString();
}

void MainWindow::getAllList(){
    setFixedSize(566,size().height());
    //resize(566,size().height());
    ui->inFileButton_2->setEnabled(false);
    initExcel(inExcel);
    list.clear();
    //QMap<QString,QString> One;
    ui->textEdit->setText("");
    for(int i = row_start; i < row_start + count - 1;++i){
        QString Number = getCellByExcel(i+1,col_start+1);
        QString Name = getCellByExcel(i+1,col_start+2);
        list.insert(Number,Name);
        ui->textEdit->setText(ui->textEdit->toPlainText()+QString("%1-%2\n").arg(Number).arg(Name));
        ui->status_label->repaint();
    }
    if(list.isEmpty())
        ui->inFileButton_2->setEnabled(true);
    else
        ui->exportButton->setEnabled(!(ui->inFileButton->isEnabled()||ui->inFileButton_2->isEnabled()||ui->inFileButton_3->isEnabled()));
    ui->status_label->setText(QStringLiteral("文件分析完毕..."));
    if(excel){
        excel->dynamicCall("Quit()");
        delete excel;
        excel = 0;
    }
}

void MainWindow::initWord(const QString &path){
    qDebug()<<path;
//    ui->status_label_2->setText(QStringLiteral("正在初始化Word..."));
//    ui->status_label_2->repaint();
//    word = new QAxObject("Word.Application");
//    connect(word,SIGNAL(exception(int,QString,QString,QString)),this,SLOT(exception_1(int,QString,QString,QString)));
//    word->setProperty("Visible", false);
    ui->status_label_2->setText(QStringLiteral("正在打开文件..."));
    ui->status_label_2->repaint();
    word->querySubObject("Documents")->dynamicCall("Open(const QString&)",path);
}

void MainWindow::setVisibleNum(bool b){
    ui->numEdit->setVisible(!b);
}

void MainWindow::getModelInfo(){
    ui->inFileButton->setEnabled(false);
    initWord(inWord);
    QString str = inWord.split(QStringLiteral("实验报告_")).at(1);
    ui->numEdit->setText(str.remove(".doc"));
    ui->status_label_2->setText(QStringLiteral("正在分析文件..."));
    ui->status_label_2->repaint();
    QAxObject *document = word->querySubObject("ActiveDocument");
    if(!document){
        exception_1();
        return;
    }
    QAxObject *Tables = document->querySubObject("Tables");
    if(!Tables){
        exception_1();
        return;
    }
    QAxObject *Item = Tables
            ->querySubObject("Item(int)",1);
    if(!Item){
        exception_1();
        return;
    }
    QAxObject *cell = Item
            ->querySubObject("Cell(int,int)",2,1)
            ->querySubObject("Range()");
    if(!cell){
        exception_1();
        return;
    }
    ModelName = cell->property("Text").toString().remove(QStringLiteral("姓名： ")).remove("\r\07").trimmed();
    delete cell;
    cell = Item
            ->querySubObject("Cell(int,int)",2,2)
            ->querySubObject("Range()");
    if(!cell){
        exception_1();
        return;
    }
    ModelNum = cell->property("Text").toString().remove(QStringLiteral("学号：")).remove("\r\07").trimmed();
    ui->nameEdit->setText(ModelName);
    ui->nameEdit->repaint();
    ui->idNum->setText(ModelNum);
    ui->idNum->repaint();
    ui->status_label_2->setText(QStringLiteral("分析完毕..."));
    ui->status_label_2->repaint();
    if(ui->nameEdit->text().isEmpty() || ui->idNum->text().isEmpty())
        ui->inFileButton->setEnabled(true);
    else
        ui->exportButton->setEnabled(!(ui->inFileButton->isEnabled()||ui->inFileButton_2->isEnabled()||ui->inFileButton_3->isEnabled()));
    if(!word->isNull()){
        word->querySubObject("ActiveDocument")->dynamicCall("Close(boolean)", false);
    }
//    delete document;
//    delete Tables;
//    delete Item;
//    delete cell;
}

void MainWindow::on_inFileButton_3_clicked()
{
    outDir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(this,QStringLiteral("选择一个保存目录"),QDir::currentPath()));
    ui->outDirPathEdit->setText(outDir);
    ui->outDirPathEdit->repaint();
    if(!outDir.isEmpty()){
        ui->inFileButton_3->setEnabled(false);
        ui->exportButton->setEnabled(!(ui->inFileButton->isEnabled()||ui->inFileButton_2->isEnabled()||ui->inFileButton_3->isEnabled()));
    }
}

void MainWindow::startOutput(){

}

void MainWindow::on_exportButton_clicked()
{
    setFixedSize(size().width(),334);
    ui->exportButton->setEnabled(false);
    ui->progressBar->setFormat(QStringLiteral("正在导出,已完成%p%"));
    ui->progressBar->setMaximum(count-1);
    ui->progressBar->setValue(0);
    ui->progressBar->repaint();
    if(ui->numEdit->text().isEmpty()){
        ui->numEdit->setText("1");
    }
    QAxObject *documents = word->querySubObject("Documents");
    QAxObject *document;
    QMap<QString,QString>::iterator iter = list.begin();
    for(int i = 0;i < count - 1;++i,++iter){
        qDebug()<<-1;
        documents->dynamicCall("Add(QString)",inWord);
        qDebug()<<0;
        document = word->querySubObject("ActiveDocument");
        qDebug()<<1;
        qDebug()<<2;
        WordStrReplace(ModelName,iter.value(),document);
        word->setProperty("Visible",false);
        qDebug()<<22;
        WordStrReplace(ModelNum,iter.key(),document);
        word->setProperty("Visible",false);
        QString savepath = QDir::toNativeSeparators(outDir+"/"+ui->lineEdit->text()
                .replace(QStringLiteral("[学号]"),iter.key())
                .replace(QStringLiteral("[姓名]"),iter.value())
                .replace(QStringLiteral("[实验序号]"),ui->numEdit->text()));
        qDebug()<<savepath;
        document->dynamicCall("SaveAs(const QString&)", savepath);
        documents->dynamicCall("Close()");
        qDebug()<<3;
        ui->progressBar->setValue(ui->progressBar->value()+1);
    }
    ui->progressBar->setFormat(QStringLiteral("导出完毕!"));
    ui->inFileButton->setEnabled(true);
    ui->inFileButton_2->setEnabled(true);
    ui->inFileButton_3->setEnabled(true);
}

bool MainWindow::WordStrReplace(const QString& replace_as,const QString replace_to,QAxObject *word){
    QAxObject *select = word->querySubObject("Range()");
    QAxObject *find = select->querySubObject("Find");
    find->dynamicCall("ClearFormatting()");
    find->dynamicCall("Execute(const QString&)",replace_as);
    select->dynamicCall("Select()");
    return select->setProperty("Text",replace_to);
}

void MainWindow::on_aboutBtn_clicked()
{
    about aboutdlg;
    aboutdlg.exec();
}
